#include "ringblkbuf.h"

void ringblkbuf_init(ringblkbuf_t *prbb)
{
    for(uint32_t i = 0; i < MAX_COUNT-1; i++)
    {
        prbb->buf[i].pnext = &(prbb->buf[i+1]);
    }
    prbb->buf[MAX_COUNT-1].pnext = &(prbb->buf[0]);
    prbb->phead = &prbb->buf[0];
    prbb->ptail = &prbb->buf[0];
    prbb->current_count = 0;
}

uint8_t ringblkbuf_read(ringblkbuf_t *prbb,uint8_t *pdata, uint8_t len)
{
    if(prbb->current_count == 0 || len > DATA_SIZE)
    {
        return 0;
    }
    else
    {
        for(uint8_t i = 0; i < len; i++)
        {
            pdata[i] = prbb->phead->data[i];
            prbb->phead->data[i] = 0;
        }
        prbb->phead = prbb->phead->pnext;
        prbb->current_count--;
        return len;
    }
}

uint8_t ringblkbuf_write(ringblkbuf_t *prbb,uint8_t *pdata,uint8_t len)
{
    if(prbb->current_count==MAX_COUNT || len > DATA_SIZE)
    {
        return 0;
    }
    else
    {
        for(uint8_t i = 0; i < len; i++)
        {
            prbb->ptail->data[i] = pdata[i];
        }
        prbb->ptail = prbb->ptail->pnext;
        prbb->current_count++;
        return len;
    }
}
